﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.UI.WebControls;
using Controllers;

namespace Web
{
    public partial class PersonalMove : System.Web.UI.Page
    {
        protected IEnumerable<File> docDtoes;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;
                docDtoes = ctx.ExecuteQuery<File>(
                        @"with t as(SELECT Id,Pid,Name,CreatTime,OwnerId,OrderNo,1 lvl FROM Files
  where FileClass=0 and OwnerId={0} and Pid is null and Type='dir'
  union all
  select b.Id,b.Pid,CAST(REPLICATE('----',lvl)+b.Name as nvarchar(100)),b.CreatTime,b.OwnerId,b.OrderNo,1+lvl
  from Files b,t where b.Pid=t.Id and b.Type='dir')
  select Id,Pid,Name,CreatTime,OwnerId,OrderNo from t;",ebi.Id).ToList();
                _constructTree(null);
                int id = int.Parse(Request.QueryString["id"]);
                File f = ctx.Files.Single(r => r.Id == id);
                ddlFolder.Value = f.Pid.ToString();
            }
        }

        private void _constructTree(int? id)
        {
            IEnumerable<File> selDtoes = docDtoes.OrderBy(r => r.OrderNo).Where(r => r.Pid == id);
            foreach (File d in selDtoes)
            {
                ddlFolder.Items.Add(new ListItem(d.Name, d.Id.ToString()));
                _constructTree(d.Id);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            int id = int.Parse(Request.QueryString["id"]);
            File f = ctx.Files.Single(r => r.Id == id);
            f.Pid = int.Parse(ddlFolder.Value);
            ctx.SubmitChanges();
            Response.Write("<script>window.returnValue='Succeed';window.close();</script>");
        }
    }
}